import axios from 'axios'
import MD5 from 'js-md5'
import { Message } from 'element-ui'
import {Base64} from 'js-base64'
import store from '../store'
import { getToken } from '@/utils/auth'
/*
* 对象升序排序
* */

function objKeySort(obj){
    const newKey = Object.keys(obj).sort()
    const newObj = {}
    for(let i = 0;i<newKey.length;i++){
        newObj[newKey[i]] = obj[newKey[i]]
    }
    return newObj
}

axios.defaults.withCredentials = true


//创建axios实例
const service  = axios.create({
     baseURL: process.env.BASE_API,//api 的base_url
     timeout:3000000  //请求超时时间
})


//request拦截器
service.interceptors.request.use(
     config => {
         const token = getToken() || ''
         const options = Object.assign({token},config.data)

         const urlParameter = {
             sign:'',
             timestamp:parseInt(new Date().getTime()) / 1000,
             v:2.0
         }


         // post-body数据转换为FormData格式
         const formData = new FormData()
         for (const k  in options){
             formData.append(k,options[k])
         }


         //对象排序、合并对象options&urlParameter
         let params  = JSON.parse(JSON.stringify(options))
         params = Object.assign(params,urlParameter)
         params = objKeySort(params)
         urlParameter.sign ='jxx'
         for(var a in params) {
             if(a !== 'sign' && typeof params[a] !== 'object'){
                 urlParameter.sign += a + params[a]
             }
         }

         urlParameter.sign += 'jxx'
         urlParameter.sign = Base64.encode(urlParameter.sign)
         urlParameter.sign = MD5(urlParameter.sign).toUpperCase()
         config.url += '?'
         Object.keys(urlParameter).forEach((key,index) =>{
               if(index === 0){
                   config.url += key + '=' + urlParameter[key]
               }else{
                   config.url += '&' + key + '=' + urlParameter[key]
               }
         })

         config.data  = formData
         return config
     },
     error => {
         Promise.reject(error)
     }
)

//response 拦截器
service.interceptors.response.use(
     response => {
         const res = response.data
         if(res.status !== 1){
            Message({
                message:res.msg || '服务器错误',
                type:'error',
                duration:3*1000
            })


            // 3 未登录,请重新登录
            if(res.status === 3){
                store.dispatch('FedLogOut').then(() => {
                    Message({
                        message:'登陆失效',
                        type:'error',
                        duration:2*1000
                    })
                    setTimeout(() => {
                        location.reload()
                    }, 2500);
                })
            }

            return Promise.reject('error')
         }else{
             return response.data
         }
     },
     error => {
         console.log('err' + error) // for debug
         Message({
             message:error.msg,
             type:'error',
             duration: 5 * 1000
         })
         return Promise.reject(error)
     }
)
export default service
